package com.zhentao.login.filter;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.login.utils.JwtToken;
import com.zhentao.login.utils.Result;
import com.zhentao.nlz.project.login.TUser;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class JwtFilter implements Filter {

    @Resource
    JwtToken jwtToken;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        System.err.println(request.getRequestURI());
        //放行/user/login
        if(request.getRequestURI().equals("/user/login")){
            filterChain.doFilter(request,response);
            return;
        }
//        获取请求头token
        String token = request.getHeader("token");
        System.err.println(token);
// 检查 token 是否为 null 或者为空
        if (token == null || token.isEmpty()) {
            // 如果 token 不存在，则直接放行或者返回错误信息
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(JSON.toJSONString(Result.error("未找到有效的 token")));
            return;
        }
        String substring = token.substring(1, token.length() - 1);
        System.err.println(substring);
        if(StringUtils.checkValNull(substring)){
            filterChain.doFilter(request,response);
            return;
        }
        System.out.println(substring);
//        对token进行解析，报错给与信息提示
        TUser user= (TUser) jwtToken.getLoginUser(substring);
        if(user==null){
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(JSON.toJSONString(Result.error("异常，请联系管理员")));
            return;
        }

//        对登录用户进行认证
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);
    }
}
